<?php

namespace addons\exam\controller;

use addons\exam\enum\CommonStatus;
use addons\exam\enum\ExamMode;
use addons\exam\enum\UserScoreType;
use addons\exam\library\ExamService;
use addons\exam\library\ScoreService;
use addons\exam\model\CateModel;
use addons\exam\model\GradeModel;
use addons\exam\model\PaperModel;
use addons\exam\model\PaperOrderModel;
use addons\exam\model\QuestionModel;
use addons\exam\model\UserModel;

use app\admin\model\exam\GradeDetail;

use app\common\services\AnswerService;
use think\Config;
use think\Request;
use think\Cache;
use think\Db;
use think\helper\Arr;
use think\Exception;

use app\common\model\Config as ConfigModel;
use app\common\services\GradeLogService; // 考试记录
use app\admin\model\exam\QuestionCollectModel;
use app\common\model\GradeLog as GradeLogModel;
use app\common\services\UrlService;
use app\common\model\Sysmessage as SysmessageModel;

/**
 * 试卷接口
 */
class Paper extends Base
{
    protected $noNeedLogin = ['index'];
    protected $noNeedRight = ['*'];
    protected $user;

    /**
     * 查询出分类下的试卷
     */
    public function index()
    {
        $cate_id = input('cate_id/d', '0');
        $sort    = input('sort/s', '');
        $now     = time();

        $query = PaperModel::with([
            'cates' => function ($query) {
                $query->withField('id, name');
            }
        ])
            ->where('status', CommonStatus::NORMAL)
            ->where('is_only_room', 0)// 过滤仅考场使用的试卷
            ->whereRaw("((start_time = 0 and end_time = 0) or (start_time < {$now} and end_time > {$now}))");

        // 分类
        if ($cate_id) {
            $child_cate_ids = CateModel::getChildId($cate_id);
            array_push($child_cate_ids, $cate_id);
            $query->whereIn('cate_id', $child_cate_ids);
        }
        // 排序
        if ($sort && $sort != 'null') {
            $sort     = explode('|', $sort);
            $field    = $sort[0];
            $order_by = $sort[1];

            $field    = in_array($field, ['join_count']) ? $field : 'join_count';
            $order_by = $order_by == 'desc' ? 'desc' : 'asc';

            $query->order("{$field} $order_by");
        }

        $list = $query->paginate(15, true);
        $this->success('', ['list' => $list]);
    }



    /**
     * ICAO试卷
     *
     * @return void
     */
    public function getPaper(){

        $type = input('type/d', 0);
        if(empty($type)){
            return $this->error('参数错误');
        }
        $pass   = input('pass/d',0);

        // set = 0 创建记录
        // set = 1 不创建记录
        $set    = input('set/d',0);

        $user_id   = $this->auth->id;

        // 添加记录
        $add['user_id']   = $user_id;
        $add['user_name'] = $this->auth->nickname;
        
        $part_type = QuestionModel::TYPE_PART;
        $paper_id  = 0;

        $question_cache_key = 'question:'.$user_id.'_'.$type.'_'.$pass;

        if( ($type == 1) && ($pass == 0) ){

            //  添加记录
            $add['type']      = 1;
            $add['type_name'] = '初考';
            $cache_key = 'getPart1:'.$user_id;
            if($set == 0){

                $log_id    = GradeLogService::add($add);
                
                Cache::set($cache_key,$log_id,600);
                Cache::pull($question_cache_key);
            }else{
                $log_id    = Cache::get($cache_key);
            }
            

            // 录音测试题
            $question_id = ConfigModel::where('name','part_0')->value('value');
            $questions_data['Part0'] = QuestionModel::getQuestion($question_id)['data'] ?? [];

            // 获取Part1试题
            $paper_id = ConfigModel::where('name','part_1')->value('value');
            $question_data = ExamService::getExamQuestion($paper_id);

            $questions_data['Part1']['list'] = collection($question_data)->toArray()['questions'] ?? [];
            $questions_data['Part1']['paper_id'] = collection($question_data)->toArray()['paper']['id'];
            $questions_data['Part1']['desc'] = collection($question_data)->toArray()['paper']['desc'] ?? [];
            $questions_data['Part1']['desc_audio'] = collection($question_data)->toArray()['paper']['desc_audio'] ?? '';

            $result['questions'] = $questions_data;
            $result['log_id']    = $log_id; // 记录ID
            
            
            $this->success('',$result);
        }elseif ( ($type == 1) && ($pass == 1) ) {

            // 热身题
            $hot_paper_id   = ConfigModel::where('name','hot_id')->value('value');
            $hot_question_data = QuestionModel::getQuestion($hot_paper_id)['data'] ?? [];
            
            // 获取Part2试题
            $paper_id       = ConfigModel::where('name','part_2')->value('value');
            $question_data  = ExamService::getExamQuestion($paper_id);

            //  热身题+Part2
            $new_list = array_merge($hot_question_data,collection($question_data)->toArray()['questions']);

            
            $questions_data['Part2']['list'] = $new_list ?? [];
            $questions_data['Part2']['paper_id'] = collection($question_data)->toArray()['paper']['id'];
            $questions_data['Part2']['desc'] = collection($question_data)->toArray()['paper']['desc'] ?? [];
            $questions_data['Part2']['desc_audio'] = collection($question_data)->toArray()['paper']['desc_audio'] ?? '';

            $cache_key = 'getPart1:'.$user_id;
            $log_id    = Cache::get($cache_key);
        }elseif(($type == 2) && ($set == 0)){

            //  添加记录
            $add['type']      = 2;
            $add['type_name'] = '复考';

            $cache_key = 'getPart3:'.$user_id;
            if($set == 0){

                $log_id = GradeLogService::add($add);
                
                Cache::set($cache_key,$log_id,600);
                Cache::pull($question_cache_key);
            }else{
                $log_id    = Cache::get($cache_key);
            }

            Cache::pull($question_cache_key);
        }elseif(($type == 2) && ($set == 1)){
            $cache_key = 'getPart3:'.$user_id;
            $log_id    = Cache::get($cache_key);
        }
        

        
        if(empty(Cache::get($question_cache_key))){

            // 获取Part3试题
            $paper_id = ConfigModel::where('name','part_3')->value('value');
            $question_data = ExamService::getExamQuestion($paper_id);

            $questions_data['Part3']['list'] = collection($question_data)->toArray()['questions'] ?? [];
            $questions_data['Part3']['paper_id'] = collection($question_data)->toArray()['paper']['id'];
            $questions_data['Part3']['desc'] = collection($question_data)->toArray()['paper']['desc'] ?? [];
            $questions_data['Part3']['desc_audio'] = collection($question_data)->toArray()['paper']['desc_audio'] ?? '';

            // 获取Part4试题
            $paper_id = ConfigModel::where('name','part_4')->value('value');
            $question_data = ExamService::getExamQuestion($paper_id);

            $questions_data['Part4']['list'] = collection($question_data)->toArray()['questions'] ?? [];
            $questions_data['Part4']['paper_id'] = collection($question_data)->toArray()['paper']['id'];
            $questions_data['Part4']['desc'] = collection($question_data)->toArray()['paper']['desc'] ?? [];
            $questions_data['Part4']['desc_audio'] = collection($question_data)->toArray()['paper']['desc_audio'] ?? '';
            
            Cache::set($question_cache_key,$questions_data,600);
        }else{
            $questions_data = Cache::get($question_cache_key);
        }

        
        $result['questions'] = $questions_data;
        $result['log_id']    = $log_id;
        $this->success('',$result);
    }


    /**
     * 模拟考提交
     *
     * @return void
     */
    public function checkPaper(){

        $user_id   = $this->auth->id;
        $check_key = 'checkPaper:'.$user_id;
        $this->checkRepeatKey($check_key);

        $this->request->filter(['strip_tags', 'trim']);
        $questions  = $this->request->post('questions/a',[]);
        $paper_id   = $this->request->post('paper_id/d',0);
        $grade_id = $this->request->post('grade_id',0);
        if( empty($questions) || empty($paper_id) ){
            return $this->error('参数错误');
        }

        $log_id = $this->request->post('log_id/d',0); // 模拟考试记录ID
        $time   = time();

        // 提交part
        $type       = $this->request->post('type',1);
        switch ($type) {
            case 1:

                // Part1
                $result = ExamService::paperExam($user_id, $paper_id, $questions, $time, $paper);
                $result['score'] ?? 0;  // 分数

                $result['pass'] = 1;
                if($result['score'] < 20){
                    // 若此部分等级低于2级，终止考试，考试结束。
                    // $result['pass'] = 0;
                    $result['pass'] = 1;
                    $level = 3;
                }elseif ( (21 <= $result['score']) && ($result['score'] <= 24) ) {
                    $level = 3;
                }elseif ( (25 <= $result['score']) && ($result['score'] <= 40) ) {
                    $level = 4;
                }elseif ( (41 <= $result['score']) && ($result['score'] <= 45) ) {
                    $level = 5;
                }elseif ( (46 <= $result['score']) && ($result['score'] <= 50) ) {
                    $level = 5;
                }

                Db::startTrans();
                try{

                    // 记录考试成绩
                    $grade = GradeModel::create(array_merge(
                        $result,
                        [
                            'cate_id'  => $paper['cate_id'],
                            'user_id'  => $user_id,
                            'paper_id' => $paper_id,
                            'log_id'   => $log_id,
                        ],
                        [
                            'date' => date('Y-m-d'),
                        ]), true);
                    
                    $saveAll = [];
                    foreach ( $questions as $value) {
                        
                        $all['user_id']     = $user_id;
                        $all['question_id'] = $value['id'];
                        $all['grade_id']    = $grade->id;
                        $all['content']     = $value['answer'];
                        $all['createtime']  = time();
                        $all['updatetime']  = time();
                        $all['paper_id']    = $paper_id;
                        $saveAll[] = $all;
                    }
                    
                    $detail = new GradeDetail;
                    $detail->saveAll($saveAll);
                    
                    Db::commit();    
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }

                $result['log_id']   = $log_id;
                return $this->success('success',$result);
                break;
            case 2:
            case 3:
            case 4:
                
                // Part2
                Db::startTrans();
                try{
                    
                    $result = ExamService::paperExam($user_id, $paper_id, $questions, $time, $paper);
                    
                    $a = array_merge(
                        $result,
                        [
                            'cate_id'  => 15,
                            'user_id'  => $user_id,
                            'paper_id' => $paper_id,
                            'log_id'   => $log_id,
                        ],
                        [
                            'date' => date('Y-m-d'),
                        ]);
                    if($grade_id){
                        return json(['code'=>1]);
                    }
                    // 记录考试成绩
                    $grade = GradeModel::create(array_merge(
                        $result,
                        [
                            'cate_id'  => 15,
                            'user_id'  => $user_id,
                            'paper_id' => $paper_id,
                            'log_id'   => $log_id,
                        ],
                        [
                            'date' => date('Y-m-d'),
                        ]), true);
             
                    $saveAll = [];
                    foreach ( $questions as $value) {
                        
                        $all['user_id']     = $user_id;
                        $all['question_id'] = $value['id'];
                        $all['grade_id']    = $grade->id;
                        $all['content']     = json_encode($value, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
                        $all['createtime']  = time();
                        $all['updatetime']  = time();
                        $all['paper_id']    = $paper_id;
                        $saveAll[] = $all;
                    }
                  
                    $detail = new GradeDetail;
                    $detail->saveAll($saveAll);

                    Db::commit();    
                } catch (\Exception $e) {
                    // 回滚事务
                    Db::rollback();
                    $this->error($e->getMessage());
                }
               
                break;
            // case 3:

            //     // Part3
                

            //     break;
            // case 4:

            //     // Part4
                
            //     break;
            default:
                # code...
                break;
        }
        
        return $this->success('success');
        // return $this->success('success',$result);
    }


    /**
     * 900句提交
     *
     * @return void
     */
    public function checkWordPaper(){

        $user_id   = $this->auth->id;
        $check_key = 'checkWordPaper:'.$user_id;
        $this->checkRepeatKey($check_key);

        $this->request->filter(['strip_tags', 'trim']);
        $questions  = $this->request->post('questions/a',[]);
        $paper_id   = $this->request->post('paper_id/d',0);
        if( empty($questions) || empty($paper_id) ){
            return $this->error('参数错误');
        }

        $time = time();
        Db::startTrans();
        try{

            $name = ConfigModel::where(['value' => $paper_id,'group'=>'paper'])->value('name');
            switch ($name) {
                case 'word_3':
                    $level = 3;
                    $type_name = '3级自测';
                    break;
                case 'word_4':
                    $level = 4;
                    $type_name = '4级自测';
                    break; 
                case 'word_5':
                    $level = 5;
                    $type_name = '5级自测';
                    break;
                case 'test_id':
                    //  套题自测评级
                    $level = 3;
                    $type_name = '套题自测';
                    break;
                default:
                    $level = 3;
                    break;
            }

            //  添加记录
            $add['user_id']   = $user_id;
            $add['user_name'] = $this->auth->nickname;
            $add['type']      = 3;
            $add['type_name'] = $type_name;
            $add['level']     = $level;
            $log_id = GradeLogService::add($add);

            $result = ExamService::paperExam($user_id, $paper_id, $questions, $time, $paper);
        
            // 记录考试成绩
            $grade = GradeModel::create(array_merge(
                $result,
                [
                    'cate_id'  => $paper['cate_id'],
                    'user_id'  => $user_id,
                    'paper_id' => $paper_id,
                    'log_id'   => $log_id,
                    'level'    => $level
                ],
                [
                    'date' => date('Y-m-d'),
                ]), true);
           
            $saveAll     = [];
            $total_score = 0;
            foreach ( $questions as $value) {
                
                $all['user_id']     = $user_id;
                $all['question_id'] = $value['id'];
                $all['grade_id']    = $grade->id;
                $all['content']     = json_encode($value, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE);
                $all['createtime']  = time();
                $all['updatetime']  = time();
                $all['paper_id']    = $paper_id;
                $all['score']       = $value['total_score'] ?? 0;
                $saveAll[] = $all;

                $total_score += $value['total_score'];
            }
          
            $detail = new GradeDetail;
            $detail->saveAll($saveAll);

            //  更新分数
            $num         = count($saveAll) ?? 1;
            $total_score = bcdiv($total_score,$num,1);
            GradeModel::where(['id' => $grade->id])->update(['total_score' => $total_score]);
            GradeLogModel::where(['id' => $log_id])->update(['total_score' => $total_score]);

            Db::commit();
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        return $this->success('success');
    }


    /**
     * 获取学员900句自测记录
     *
     * @return void
     */
    public function getGradeLog(){

        $type = input('type/d',3);

        if($type == 3){
            $data['type'] = $type;
        }else{
            $data['type'] = ['<',3];
        }
        
        $page_info = $this->getPerPage();
        $user_id = $this->auth->id;
        $data['user_id'] = $user_id;
        $list     = GradeLogService::list($data,$page_info);

        foreach($list['data'] as &$value){
            $value['createtime'] = date('Y-m-d',$value['createtime']);
        }
        return $this->success('success',$list);
    }


    /**
     * 专家点评申请
     *
     * @return void
     */
    public function getGradeAdd(){

        $user_id = $this->auth->id;
        $key = 'getGradeAdd:'.$user_id;
        $this->checkRepeatKey($key);

        $id     = input('id/d',0);
        if(empty($id)){
            return $this->error('参数错误');
        }

        // 用户ID
        
        $num_comments = UserModel::where('id',$user_id)->value('num_comments');
        if($num_comments <= 0){
            return $this->error('专家点评次数为0');
        }

        $info = GradeLogService::info($id);
        if($info['status'] == 1){
            return $this->success('已申请专家点评',['status'=>1]);
        }


        Db::startTrans();
        try{

            $data['id']     = $id;
            $data['status'] = 1;
            GradeLogService::edit($data);
      
            UserModel::where('id',$user_id)->setDec('num_comments');
            
            SysmessageModel::addLog($user_id,'专家点评');
            
            Db::commit();    
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->error($e->getMessage());
        }
        
        return $this->success('success',['status'=>1]);
    }

    /**
     * 获取学员900句自测记录
     *
     * @return void
     */
    public function getGradeInfo(){

        $id = input('id/d',0);
        if(empty($id)){
            return $this->error('参数错误');
        }

        $user_id = $this->auth->id;
        
        $user    = UserModel::where(['id' => $this->auth->id])->field('id,nickname,num_comments')->find();
        $result['user'] = $user;

        $list    = GradeLogService::detail($id);
        
        $ids     = array_column($list,'question_id');
        $collect_ids = QuestionCollectModel::where(['user_id'=>$user_id])->where('question_id','IN',$ids)->column('question_id');
        $questions   = QuestionModel::where('id','IN',$ids)->column('title_audio','id');

        foreach($list as &$value){
            $value['content']   = json_decode($value['content'],true);
            $value['collected'] = in_array($value['question_id'], $collect_ids);

            $title_audio     = '';
            if(isset($questions[$value['question_id']])){
                $title_audio = urlService::getFileUrl( $questions[$value['question_id']] );
            }
            $value['title_audio'] =  $title_audio;
        }

        $result['list'] = $list;
        $info = GradeLogModel::where(['id' => $id])->find();
        $info['createtime'] = date('Y-m-d',$info['createtime']);
        $result['info']     = $info;
        $result['info']['accuracy_num']     = floor($info['accuracy_score']/20) ?? 0;
        $result['info']['fluency_num']      = floor($info['fluency_score']/20) ?? 0;
        $result['info']['standard_num']     = floor($info['standard_score']/20) ?? 0;
        $result['info']['zhuanjialink'] = Config::get('site.zhuanjialink');
        return $this->success('success',$result);
    }


    
     /**
     * 交卷
     */
    public function submit22()
    {  
       
        $user_id   = $this->auth->id;
        $check_key = 'select_paper_token:'.$user_id;
        $this->checkRepeatKey($check_key);
        
        $request       = Request::instance();
        $param         = $request->param();
        
        $user_id       = $this->auth->id;
        $paper_id      = $param['paper_id'];
        $questions     = $param['questions'];
        $start_time    = time();
        if (!$user_id || !$paper_id || !$questions) {
            $this->error('提交数据有误');
        }
        
        $questions = htmlspecialchars_decode($questions);
        $questions = html_entity_decode($questions);
        $questions = json_decode($questions,true);
        
        $result = ExamService::paperExamCheck($user_id, $paper_id, $questions, $start_time, $paper);
        
        
        // 记录考试成绩
        GradeModel::create(array_merge(
            $result,
            [
                'cate_id'  => $paper['cate_id'],
                'user_id'  => $user_id,
                'paper_id' => $paper_id,
            ],
            [
                'date' => date('Y-m-d'),
            ]), true);
        
        // 下一套试卷
        $redis_key = 'select_paper:'.$user_id;
        $cache     = Cache::get($redis_key);
        
        // 获取门派选择试卷分类ID
        $cate_id   = Config::where('name','select_paper')->value('value');
        $ids       = PaperModel::where(['cate_id' => $cate_id])->column('id');
        $total     = PaperModel::where(['cate_id' => $cate_id])->count();
        if(isset($ids[$cache+1])){
            
            // 门派选择下一套试卷
            $list   = ExamService::getExamQuestion($ids[$cache+1], 0);
            
            Cache::inc($redis_key);
            
            $return_data['paper_id'] = $ids[$cache+1];
            $return_data['status'] = 1;
            $return_data['num']    = (Cache::get($redis_key)+1).'/'.$total;
            $return_data['total']  = count($list);
            $return_data['list']   = $list;
            return $this->success('', $return_data);
        }
        
        
        // 获取用户推荐岗位ID
        $cache_key   = 'job_id:'.$user_id;
        $job_cache   = Cache::get($cache_key);
        
        // 岗位对应ID
        $option = [
            'A' => 1,
            'B' => 4,
            'C' => 2,
            'D' => 5,
            'E' => 3
        ];
        
        $cate_id     = $option[$job_cache] ?? 5;
        $student_job = StudentJob::where(['id' => $cate_id])->field('id,name,desc')->find();
        
        // 门派选项试卷完成
        $return_data['status'] = 2;
        $return_data['desc']   = $student_job['desc'];
        $return_data['id']     = [$cate_id];
        return $this->success('', $return_data);
    }
    




    /**
     * 900句试卷
     *
     * @return void
     */
    public function getWordPaper(){

        $type = input('type/d', 0);
        if(empty($type)){
            return $this->error('参数错误');
        }

        $paper_id = 0;
        switch ($type) {
            case 1:
                $paper_id = ConfigModel::where('name','test_id')->value('value');
                break;
            case 2:
                $paper_id = ConfigModel::where('name','word_3')->value('value');
                break;
            case 3:
                $paper_id = ConfigModel::where('name','word_4')->value('value');
                break;
            case 4:
                $paper_id = ConfigModel::where('name','word_5')->value('value');
                break;
            default:
                # code...
                break;
        }

        if(empty($paper_id)){
            return $this->error('type参数错误');
        }

        // 获取试卷题目
        $question_data = ExamService::getExamQuestion($paper_id);
        $this->success('',$question_data);
    }




    /**
     * 试卷取题接口
     */
    public function getExamQuestion()
    {
        $paper_id = input('paper_id/d', 0);
        $room_id  = input('room_id/d', 0);

        // 验证是否需要绑定手机号
        UserModel::isMustBindMobile($this->auth->getUser());

        // 预创建考场考试记录
        $room_grade_id = ExamService::preRoomGrade($room_id, $this->auth->id);

        // 获取试卷题目
        $question_data = ExamService::getExamQuestion($paper_id, $room_id);

        $this->success('', array_merge($question_data, ['room_grade_id' => $room_grade_id]));
    }





    /**
     * 单次提交
     *
     * @return void
     */
    public function save(){

        $this->request->filter(['strip_tags', 'trim']);
        $questions  = $this->request->post('questions/a',[]);
        $course_id  = $this->request->post('course_id/d',0);

        if(empty($course_id)){
            return $this->error('参数错误');
        }

        // 校验答案
        $result = ExamService::saveAll($course_id,$questions,$this->auth->id);
        AnswerService::setAnswer($course_id,$this->auth->id,$questions);
        return $this->success('success',$result);
    }



    /**
     * 单次提交
     *
     * @return void
     */
    public function submit(){
        
        $this->request->filter(['strip_tags', 'trim']);
        $id         = $this->request->post('id/d',0);
        $answer     = $this->request->post('answer/a','');

        if(empty($id) || empty($answer)){
            return $this->error('参数错误');
        }

        /**
         * 校验答案
         */
        $result = ExamService::submit($id,$answer);
        return $this->success('success',$result);
    }
    

    /**
     * 交卷
     */
    public function submitAll()
    {
        $request       = Request::instance();
        $user_id       = $this->auth->id;
        $paper_id      = $request->post('paper_id/d', 0);
        $questions     = $request->post('questions/a', []);
        $start_time    = $request->post('start_time/d', time());
        $room_id       = $request->post('room_id/d', 0);
        $room_grade_id = $request->post('room_grade_id/d', 0);

        if (!$user_id || !$paper_id || !$questions) {
            $this->error('提交数据有误' . $user_id);
        }

        // 考场考试
        if ($room_id) {
            $result = ExamService::roomExam($user_id, $room_id, $room_grade_id, $questions, $start_time, $paper, $room, $is_makeup, $room_grade_log);

            // 不记录用户答案
            // if (getConfig('system_config', 'record_exam_open', 0) == 0) {
            //     unset($result['user_answers']);
            // }

            // 记录考场考试成绩
            $room_grade_log->allowField(true)->save(
                array_merge(
                    $result,
                    [
                        'cate_id'   => $paper['cate_id'],
                        'user_id'   => $user_id,
                        'paper_id'  => $paper_id,
                        'is_makeup' => $is_makeup,
                        'is_pre'    => 0, // 提交成绩后不再为预创建标记
                    ],
                    [
                        'exam_mode' => ExamMode::ROOM,
                    ]
                )
            );

            // 试卷考试得积分
            $result['point'] = [
                'get_point' => ScoreService::getScore($this->auth->id, UserScoreType::ROOM, $room_grade_log),
                'type'      => UserScoreType::getDescription(UserScoreType::ROOM)
            ];
        } else {
            $result = ExamService::paperExam($user_id, $paper_id, $questions, $start_time, $paper);

            // 记录考试成绩
            $paper_grade_log = GradeModel::create(array_merge(
                $result,
                [
                    'cate_id'  => $paper['cate_id'],
                    'user_id'  => $user_id,
                    'paper_id' => $paper_id,
                ],
                [
                    // 'exam_mode' => ExamMode::PAPER,
                    'date' => date('Y-m-d'),
                ]), true);

            // 试卷考试得积分
            $result['point'] = [
                'get_point' => ScoreService::getScore($this->auth->id, UserScoreType::PAPER, $paper_grade_log),
                'type'      => UserScoreType::getDescription(UserScoreType::PAPER)
            ];
        }
        return json($result);
    }


    /*
     * 查看错题
     * Robin
     * @param $ids
     */
    public function error_ids($ids)
    {
        $questions = QuestionModel::whereIn('id', ($ids))->select();
        $this->success('', $questions);
    }

    /**
     * 检查是否需要支付
     */
    public function checkPay()
    {
        $paper_id = input('paper_id/d', 0);
        $room_id  = input('room_id/d', 0);

        if (!$paper_id) {
            $this->error('考试试卷参数有误');
        }
        if (!$paper = PaperModel::get($paper_id)) {
            $this->error('考试试卷数据不存在');
        }
        if ($room_id) {
            $this->success('', ['status' => 1]);
        }

        // 检测题库是否需要付费
        $result = CateModel::checkPay($paper['cate_id'], $this->auth->id);
        if ($result['status'] == 2) {
            // 需要支付直接返回
            $this->success('', $result);
        }
        // dd($result);

        // 检测试卷是否需要付费
        $result = PaperModel::checkPay($paper, $this->auth->id, false, $room_id);
        $this->success('', $result);
    }

    /**
     * 创建考试订单
     */
    public function createOrder()
    {
        $paper_id = input('paper_id/d', 0);
        $room_id  = input('room_id/d', 0);

        if (!$paper_id) {
            $this->error('考试试卷参数有误');
        }
        if (!$paper = PaperModel::get($paper_id)) {
            $this->error('考试试卷数据不存在');
        }

        $result = PaperModel::checkPay($paper, $this->auth->id, false, $room_id);
        if ($result['status'] != 2) {
            $this->error('该考试试卷无须付费，请尝试重新进入');
        }

        if (PaperOrderModel::hasUsableOrder($paper_id, $this->auth->id)) {
            $this->error('您已付费，无须重复支付，请尝试重新进入');
        }

        $order   = PaperOrderModel::createOrder($paper['id'], $this->auth->id, $result['is_member'] ? $paper['member_price'] : $paper['price']);
        $payment = PaperOrderModel::createPayment($this->auth->id, $order['order_no'], $order['amount']);

        $this->success('', [
            'order'   => $order,
            'payment' => $payment
        ]);
    }

}
